"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 硬件故障类--disk
Case Name   : 数据备份时主节点IOwait高
Create At   : 2021/07/09
@zou_jialiang0505328126
Description :
    1.主节点注入ioWait高故障
    2.主节点执行备份指令
    3.清理故障
    4.使用备份文件恢复系统
    5.对备库进行build
    6.查询数据是否与备份时一致
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.成功
    6.数据一致，且主备一致
History     :
    Modified 2021/9/1 @wan005:适配最新CFE故障打印,并修改用例还原时需要清理故障
"""

import unittest
import os
import time
from yat.test import Node, macro
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Logger import Logger


class DiskIOwait(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info(
            '---------Opengauss_Reliability_Hardware_Case056:开始执行---------')
        self.primary_root_node = Node(node='PrimaryRoot')
        self.primary_user_node = Node(node='PrimaryDbUser')
        self.sta1_dbuser = Node(node='Standby1DbUser')
        self.sta2_dbuser = Node(node='Standby2DbUser')
        self.com = Common()
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.sta_1_sh = CommonSH('Standby1DbUser')
        self.sta_2_sh = CommonSH('Standby2DbUser')
        self.constant = Constant()
        self.parent_path = os.path.dirname(macro.DB_INSTANCE_PATH)
        self.backup_path = os.path.join(self.parent_path, 'base_backup')

        result = self.primary_sh.executDbSql(
            'show wal_sender_timeout;')
        self.log.info(f"wal_sender_timeout is {result}")
        self.wal_sender_timeout = result.strip().splitlines()[-2]

        cmd = f"df -h {macro.DB_INSTANCE_PATH}"
        self.log.info(cmd)
        msg = self.primary_root_node.sh(cmd).result()
        self.log.info(msg)
        self.dir = msg.splitlines()[-1].split()[-1].strip()

        self.log.info('-----------修改wal_sender_timeout------------------')
        result = self.primary_sh.executeGsguc('reload',
                                              self.constant.GSGUC_SUCCESS_MSG,
                                              'wal_sender_timeout=12s')
        self.assertTrue(result)

    def test_main(self):
        text = '----step1: 主节点注入ioWait高故障 expect:成功----'
        self.log.info(text)
        inject_command = f"rIO_iowait (type,dir,bs,count,time) " \
            f"values (w_iowait,{self.dir}, 10000,10000,1500)"
        result = self.com.cfe_inject(self.primary_root_node, inject_command)
        self.log.info(result)
        result = self.com.cfe_query(self.primary_root_node, "rIO_iowait")
        self.log.info(result)
        self.assertIn(self.constant.cfe_iowait_success_msg, result,
                      '执行失败:' + text)

        text = '----step2: 主节点执行备份指令 expect:成功----'
        self.log.info(text)
        shell_cmd = f'rm -rf {self.backup_path}; mkdir {self.backup_path}'
        self.log.info(shell_cmd)
        result = self.primary_user_node.sh(shell_cmd).result()
        self.log.info(result)
        result = self.primary_sh.execu_gs_basebackup(
            self.backup_path, self.primary_user_node.db_host,
            self.primary_user_node.db_port)
        self.assertIn(self.constant.BASEBACKUP_SUCCESS_MSG, result,
                      '执行失败:' + text)
        result = self.primary_user_node.sh(
            f'ls -l {self.backup_path} | grep "^-" | wc -l').result()
        self.log.info(result)
        self.assertLess(0, int(result), '执行失败:' + text)

        text = '----step3: 清理故障 expect:成功----'
        self.log.info(text)
        for i in range(3):
            result = self.com.cfe_clean(self.primary_root_node, "rIO_iowait")
            self.log.info(result)
        result = self.com.cfe_query(self.primary_root_node, "rIO_iowait")
        self.log.info(result)
        self.assertNotIn(self.constant.cfe_iowait_success_msg, result,
                      '执行失败:' + text)

        text = '----step4: 使用备份文件恢复系统 expect:成功----'
        self.log.info(text)
        result = self.primary_sh.stopDbCluster()
        self.assertTrue(result)
        shell_cmd = f'rm -rf  {macro.DB_INSTANCE_PATH}/* ;' \
            f'cp -R {self.backup_path}/* {macro.DB_INSTANCE_PATH}'
        self.log.info(shell_cmd)
        result = self.primary_user_node.sh(shell_cmd).result()
        self.log.info(result)
        time.sleep(2)
        result = self.primary_sh.startDbCluster('get_detail')
        self.log.info(result)
        result = ('Degraded' in result) or \
                 (self.constant.START_SUCCESS_MSG in result)
        self.assertTrue(result, '执行失败:' + text)
        time.sleep(2)

        text = '----step5: 对备库进行build expect:成功----'
        self.log.info(text)
        result = self.primary_sh.check_whether_need_build()
        success_msg = self.constant.BUILD_SUCCESS_MSG
        if result:
            result = self.sta_1_sh.executeGsctl('build',
                                                success_msg,
                                                '-b full')
            self.assertTrue(result, '执行失败:' + text)
            result = self.sta_2_sh.executeGsctl('build',
                                                success_msg,
                                                '-b full')
            self.assertTrue(result, '执行失败:' + text)

        text = '----step6: 查询数据是否与备份时一致 expect:数据一致，且主备一致----'
        self.log.info(text)
        result = self.sta_1_sh.check_data_consistency()
        self.assertTrue(result, '执行失败:' + text)
        result = self.sta_2_sh.check_data_consistency()
        self.assertTrue(result, '执行失败:' + text)
        nodes_tuple = (self.primary_user_node,
                       self.sta1_dbuser, self.sta2_dbuser)
        flag = self.com.check_data_sample_by_all(r'\d', *nodes_tuple)
        self.assertTrue(flag, '执行失败:' + text)

        table_dict = self.com.format_sql_result(
            self.primary_sh.executDbSql(r'\d'))
        table_name = table_dict.get('Name')
        for name in table_name:
            select_sql = f'select count(*) from {name};'
            flag = self.com.check_data_sample_by_all(select_sql,
                                                        *nodes_tuple)
            self.assertTrue(flag, '执行失败:' + text)

    def tearDown(self):
        self.log.info("-------------清理环境---------------")
        self.log.info("--------------主节点清理故障-------------")
        result = self.com.cfe_clean(self.primary_root_node, "rIO_iowait")
        self.log.info(result)
        result = self.com.cfe_query(self.primary_root_node, "rIO_iowait")
        self.log.info(result)

        self.log.info('----删除备份文件----')
        shell_cmd = f'rm -rf {self.backup_path}'
        self.log.info(shell_cmd)
        result = self.primary_root_node.sh(shell_cmd).result()
        self.log.info(result)

        self.log.info('----检查备机是否需要重建----')
        result = self.primary_sh.check_whether_need_build()
        if result:
            self.sta_1_sh.executeGsctl('build',
                                       self.constant.BUILD_SUCCESS_MSG,
                                       '-b full')
            self.sta_2_sh.executeGsctl('build',
                                       self.constant.BUILD_SUCCESS_MSG,
                                       '-b full')

        self.log.info('-----------还原wal_sender_timeout------------------')
        result = self.primary_sh.executeGsguc('reload',
                                          self.constant.GSGUC_SUCCESS_MSG,
                                          f'wal_sender_timeout='
                                          f'{self.wal_sender_timeout}')
        self.log.info(result)
        self.log.info(
            '--------Opengauss_Reliability_Hardware_Case056:执行完成--------')
